import React from 'react';
import { Upload, Modal,notification } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import http from 'axios'
import OSS from 'ali-oss'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

class App extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    disabled:this.props.disabled,
    fileList: this.props.pictureUrl?[{url:this.props.pictureUrl,status: 'done'}]:[],
  };

  handleCancel = () => this.setState({ previewVisible: false });

  componentWillReceiveProps(nextProps){
    if(nextProps.disabled!==this.state.disabled){
    this.setState({
      disabled:nextProps.disabled
    })
    }

      if(nextProps.id&&!nextProps.value) {
        return
      }
      if(nextProps.pictureUrl===nextProps.value) {
        return
      }
      if(nextProps.id&&nextProps.value) {
        this.setState({
          fileList:nextProps.value?[{url:nextProps.value,status: 'done'}]:[]
         })
        return
      }
      
      if(nextProps.pictureUrl&&nextProps.pictureUrl===this.state.fileList[0]?.url) return
    
       this.setState({
        fileList:nextProps.pictureUrl?[{url:nextProps.pictureUrl,status: 'done'}]:[]
       })
    }

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = ({ fileList }) => {
    this.setState({ fileList:fileList.filter(i=>i.status==='done') },()=>{
      this.props.setPhoto(this.state.fileList[0]?.url)
    })
  } ;

  handleMove = (file) =>{
    this.setState({
      fileList:[...this.state.fileList].filter(i=>i.status==='done')
    })
    this.props.setPhoto('')
  }

  customRequest = (file) => {
    var suffix = file.file.name.substr(file.file.name.indexOf('.')) // 获取文件后缀名
    var filename = new Date().getTime() + suffix // 为文件命名


    const token =  window.location.href.indexOf('/prd') === -1 ?localStorage.getItem('token-llx-test'):localStorage.getItem('token-llx')


    http({
      method: 'post',
      url:  window.location.href.indexOf('/prd')===-1?'http://139.224.81.105:19999/qia-cloud-filesystem/OSS/companies/getStsToken':'http://139.224.81.105:9999/qia-cloud-filesystem/OSS/companies/getStsToken',
      headers: { 'Authorization': 'Bearer ' + token}
    }).then(res => {
      const fileData = res
      var bucket = 'middle-file'
      var region = 'oss-cn-shanghai'
      var type = ''
      const client = new OSS({
        region,
        accessKeyId: fileData.accessKeyId,
        accessKeySecret: fileData.accessKeySecret,
        stsToken: fileData.stsToken,
        bucket
      })
      type = this.props.type||'image'
      client.multipartUpload(type + '/' + filename, file.file).then((result) => {
        var url = result.res.requestUrls[0]
        var length = url.lastIndexOf('?')
        var getUrl = length > 0 ? url.substr(0, length) : url // 文件最终路径

        this.setState({
          fileList:[...this.state.fileList,{url:getUrl,status: 'done'}].filter(i=>i.status==='done')
        },()=>{
          this.props.setPhoto(this.state.fileList[0].url)
        })

        


      }).catch(function(err) {
        console.log(err)
      })
  }).catch(err=>{
    notification.error({
      description:'上传失败',
      duration:1
    })
  })
}

  render() {
    const { previewVisible, previewImage, fileList, previewTitle,disabled } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div  style={{ marginTop: 8 }}>点击上传</div>
      </div>
    );
    return (
      <>
        <Upload
          action="#"
          accept="image/*"
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          onRemove={this.handleMove}
          customRequest={this.customRequest}
          maxCount={1}
          disabled={disabled} 
        >
          {fileList.length >= 1 ? null : uploadButton}
        </Upload>
        
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}

export default App;